"use client";
import React, { useState, useEffect, useRef } from "react";
import styles from "./page.module.css";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast, Toaster } from "react-hot-toast";

const Register = () => {

  // 新增：密码相关状态
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false); // 控制密码可见性
  const [passwordError, setPasswordError] = useState(""); // 密码校验错误


  const formRef = useRef(null);
  const [error, setError] = useState(null);
  const [verificationCode, setVerificationCode] = useState("");
  const [isSendingCode, setIsSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [email, setEmail] = useState("");
  const [name, setName] = useState(""); // 存储姓名用于检查
  const [isEmailExisted, setIsEmailExisted] = useState(false);
  const [isNameExisted, setIsNameExisted] = useState(false); // 标记姓名是否重复

  const router = useRouter();

  // 倒计时逻辑
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  // 检查邮箱是否存在（已有逻辑）
  const checkEmailExists = async (inputEmail) => {
    if (!inputEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(inputEmail)) {
      setIsEmailExisted(false);
      return;
    }
    try {
      const res = await fetch("/api/check-email", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: inputEmail }),
      });
      const data = await res.json();
      setIsEmailExisted(data.isExisted);
    } catch (err) {
      console.error("检查邮箱失败:", err);
    }
  };

  // 新增：检查姓名是否存在
  const checkNameExists = async (inputName) => {
    if (!inputName) {
      setIsNameExisted(false);
      return;
    }
    try {
      const res = await fetch("/api/check-name", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: inputName }),
      });
      const data = await res.json();
      setIsNameExisted(data.isExisted); // 根据接口返回标记姓名是否重复
    } catch (err) {
      console.error("检查姓名失败:", err);
    }
  };

  // 发送验证码：增加姓名不重复的判断
  const handleSendCode = async () => {
    if (!formRef.current) {
      toast.error("表单加载失败，请刷新页面");
      return;
    }
    const inputEmail = formRef.current.email.value;

    // 检查姓名是否重复
    if (isNameExisted) {
      toast.error("该用户名已被使用，请更换");
      return;
    }
    // 检查邮箱格式和是否重复（已有逻辑）
    if (!inputEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(inputEmail)) {
      toast.error("请输入有效的邮箱地址");
      return;
    }
    if (isEmailExisted) {
      toast.error("该邮箱已被注册，请更换");
      return;
    }

    setIsSendingCode(true);
    try {
      const res = await fetch("/api/send-verification-code", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: inputEmail }),
      });
      const data = await res.json();
      if (res.ok) {
        toast.success("验证码已发送至邮箱，5分钟内有效");
        setCountdown(60);
      } else {
        toast.error(data.message || "发送验证码失败");
      }
    } catch (err) {
      toast.error("网络错误，发送失败");
    } finally {
      setIsSendingCode(false);
    }
  };

  // 新增：密码校验（两次输入是否一致）
  useEffect(() => {
    if (password && confirmPassword && password !== confirmPassword) {
      setPasswordError("两次输入的密码不一致");
    } else {
      setPasswordError("");
    }
  }, [password, confirmPassword]);

  // 提交注册：增加姓名检查
  const handleSubmit = async (e) => {
    e.preventDefault();
    // 1. 此处访问的是状态变量 password（此时还未被函数内的局部变量覆盖）
    if (password !== confirmPassword) {
      setPasswordError("两次输入的密码不一致");
      return;
    }
    const inputName = e.target.name.value;
    const inputEmail = e.target.email.value;
    // 2. 关键修复：将函数内的 password 变量重命名（避免与状态变量冲突）
    const inputPassword = e.target.password.value; // 重命名为 inputPassword
    const code = e.target.verificationCode.value;

    // 检查姓名和邮箱是否重复（双重保险）
    if (isNameExisted) {
      toast.error("该用户名已被使用，请更换");
      return;
    }
    if (isEmailExisted) {
      toast.error("该邮箱已被注册，请更换");
      return;
    }

    try {
      const res = await fetch("/api/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: inputName,
          email: inputEmail,
          password: inputPassword, // 使用重命名后的变量
          verificationCode: code
        }),
      });
      const data = await res.json();

      if (res.ok) {
        toast.success("注册成功！即将跳转到登录页");
        setTimeout(() => {
          router.push("/dashboard/login?success=Account has been created");
        }, 1500);
      } else {
        // 处理后端返回的错误（包括姓名/邮箱重复）
        if (data.message.includes("用户名已被注册")) {
          setIsNameExisted(true);
        }
        if (data.message.includes("邮箱已被注册")) {
          setIsEmailExisted(true);
        }
        setError(data.message);
        toast.error(data.message || "注册失败");
      }
    } catch (err) {
      setError("网络错误，请稍后再试");
      toast.error("网络错误，请稍后再试");
    }
  };

  return (
    <div className={styles.container}>
      <h1 className={styles.title}>创建账号</h1>
      <h2 className={styles.subtitle}>请注册以查看控制台。</h2>

      <form ref={formRef} onSubmit={handleSubmit} className={styles.form}>
        {/* 姓名输入框（增加实时检查） */}
        <div>
          <input
            type="text"
            name="name"
            placeholder="用户名"
            required
            className={styles.input}
            value={name}
            onChange={(e) => {
              setName(e.target.value);
              checkNameExists(e.target.value); // 输入时触发检查
            }}
            autoComplete="new-username" // 禁用用户名自动填充

          />
          {isNameExisted && (
            <p className={styles.errorTip}>该用户名已被使用，请更换</p>
          )}
        </div>

        {/* 邮箱输入框（已有逻辑） */}
        <div>
          <input
            type="email"
            name="email"
            placeholder="邮箱"
            required
            className={styles.input}
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
              checkEmailExists(e.target.value);
            }}
            autoComplete="new-email" // 禁用邮箱自动填充

          />
          {isEmailExisted && (
            <p className={styles.errorTip}>
              该邮箱已被注册，请更换或{" "}
              <Link href="/dashboard/login" className={styles.loginLink}>登录</Link>
            </p>
          )}
        </div>

        {/* 验证码区域 */}
        <div className={styles.codeContainer}>
          <input
            type="text"
            name="verificationCode"
            placeholder="验证码"
            value={verificationCode}
            onChange={(e) => setVerificationCode(e.target.value)}
            required
            className={styles.codeInput}
            autoComplete="one-time-code" // 验证码特殊值，避免自动填充

          />
          <button
            type="button"
            onClick={handleSendCode}
            disabled={isSendingCode || countdown > 0 || isEmailExisted || isNameExisted}
            className={styles.sendCodeBtn}
          >
            {countdown > 0
              ? `重新发送 ${countdown}s`
              : isSendingCode
                ? "发送中..."
                : "发送验证码"}
          </button>
        </div>

        {/* 密码输入框 */}
        <div className={styles.passwordContainer}>
          <input
            type={showPassword ? "text" : "password"}
            name="password"
            placeholder="密码"
            required
            className={styles.input}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="new-password"
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className={styles.toggleBtn}
            aria-label={showPassword ? "隐藏密码" : "显示密码"}
          >
            <span className={showPassword ? styles.visible : styles.hidden}>
              {showPassword ? "👁️" : "👁️‍🗨️"}
            </span>
          </button>
        </div>

        {/* 确认密码输入框 */}
        <div className={styles.passwordContainer}>
          <input
            type={showPassword ? "text" : "password"}
            name="confirmPassword"
            placeholder="确认密码"
            required
            className={styles.input}
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            autoComplete="new-password"
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className={styles.toggleBtn}
            aria-label={showPassword ? "隐藏密码" : "显示密码"}
          >
            <span className={showPassword ? styles.visible : styles.hidden}>
              {showPassword ? "👁️" : "👁️‍🗨️"}
            </span>
          </button>
        </div>

        {/* 密码错误提示 */}
        {passwordError && (
          <p className={styles.errorTip}>{passwordError}</p>
        )}

        {/* 注册按钮：姓名或邮箱重复时禁用 */}
        <button
          type="submit"
          className={styles.button}
          disabled={isEmailExisted || isNameExisted}
        >
          注册
        </button>

        {error && <p className={styles.error}>{error}</p>}
      </form>

      <span className={styles.or}>- 或者 -</span>
      <Link className={styles.link} href="/dashboard/login">
        登录现有账号
      </Link>

      <Toaster position="top-right" />
    </div>
  );
};

export default Register;